<?php

/*************************************************************
 ****** данный класс реализует работу с личными сообщениями **
 ************************************************************/

class DatabaseObject_Pm extends DatabaseObject {
    
    public $_author = null;
    public $_receiver = null;
    
    public function __construct($db) {
        parent::__construct($db, 'pm', 'id');
        
        $this->add('author');
        $this->add('user');
        $this->add('text');
        $this->add('date');
        $this->add('isRead');
    }
    
    public function postLoad() {
        parent::postLoad();
        
        $this->_author = new DatabaseObject_User($this->getDb());
        $this->_receiver = new DatabaseObject_User($this->getDb());
        if ($this->author != Zend_Auth::getInstance()->getIdentity()->id)
        {
            $this->_author->load($this->author);
            $this->_receiver->load($this->user);
        }
        else 
        {
            $this->_author->load($this->user);
            $this->_receiver->load($this->author);
        }
        
       
        
        return true;
    }
    
    public function preInsert() {
        parent::preInsert();
        
        $this->isRead = 0;
        $this->date = date("Y-m-d H:i:s");
        
        return true;
    }
    
    // получение списка диалогов пользователя
    public static function GetUserDialogs($db, $userId, $limit, $offset) {
        $query = sprintf(
                "(select `user` from `pm` where `author` = %d) union (select `author` from `pm` where `user`= %d) limit %d,%d",
                $userId, 
                $userId,
                $offset,
                $limit
        );
        $to = $db->query($query)->fetchAll();
        $dialogs = array();
        for($i = 0; $i < count($to); $i++) {
            $query = sprintf(
                    "select id from `pm` where (`author` = %d and `user`= %d) or (`author` = %d and `user` = %d) order by date desc limit 1",
                    $userId,
                    $to[$i]['user'],
                    $to[$i]['user'],
                    $userId
            );
            $id = $db->query($query)->fetchObject();
            $dialogs[$i] = new DatabaseObject_Pm($db);
            $dialogs[$i]->load($id->id);
        }

        return $dialogs;
    }
    
    // получение диалога
    public static function GetDialog($db, $id1, $id2, $limit, $offset) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'u.*');
        $select->where(sprintf('(`author` = %d and `user` = %d) or (`author` = %d and `user` = %d)', $id1, $id2, $id2, $id1));
        $select->order('date');
        $select->limit($limit, $offset);
        
        $data = $db->fetchAll($select);
        
        $dialog = self::BuildMultiple($db, __CLASS__, $data);
        
        foreach($dialog as $pm) {
            $pm->_author = new DatabaseObject_User($db);
            $pm->_author->load($pm->author);
            $pm->_receiver = new DatabaseObject_User($db);
            $pm->_receiver->load($pm->user);
        }
        
        return $dialog;
    }
    
    private static function _GetBaseQuery($db, $options) {
        // инициализируем параметры
        $defaults = array('id' => array());

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        // создадим запрос
        $select = $db->select();
        $select->from(array('u' => 'pm'), array());
        
       if(isset($options['where'])) {
            $select->where($options['where']);
        }
        if(isset($options['limit'])) {
       
            $select->limit($options['offset'] . ',' . $options['limit']);
        }


        // отфильтруем записи по id (если задано)
        if (count($options['id']) > 0) {
            $select->where('u.id in (?)', $options['id']);
        }

        return $select;
    }
    
    // отмечаем в диалоге сообщения как прочитанные после отображения
    public static function MarkDialogAsRead($db, $id1, $id2) {
        $query = sprintf('update pm set isRead = 1 where `author` = %d and `user` = %d', $id1, $id2);
        //echo $query;return;
        $db->query($query);
    }
    
    // отметить все диалоги как прочтенные
    public static function MarkAllAsRead($db, $userId) {
        $query = sprintf('update pm set isRead = 1 where `user` = %d', $userId);
        
        $db->query($query);
    }
    
    // удалить все диалоги 
    public static function DeleteAll($db, $userId) {
        $query = sprintf('delete from pm  where `user` = %d or `author` = %d', $userId, $userId);
        
        $db->query($query);
    }
    
    // удалить  диалог
    public static function DeleteDialog($db, $userId, $authorId) {
        $query = ("delete from pm  where (`user` = '$userId' and author = '$authorId') or (`user` = '$authorId' and author = '$userId')");
        
        $db->query($query);
    }
    
    public static function GetUnreadCount($db, $userId) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');
        
        $where = sprintf('user = %d and isRead = 0', $userId);
        
        $select->where($where);

        return $db->fetchOne($select);
    }
}

